const app = getApp();
import { Product } from '../../pages/product/product-model.js';
var product = new Product(); 
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    user: { // 用户信息
      type: Object,
      value: ''
    },
    product: { // 商品信息
      type: Object,
      value: ''
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    showpost: false,
    imgHeight: 0,
    qrCode: "", //二维码
    diyImg:"", //个性图片
    diyImgInfo:{},
    qrCode:"", //二维码
    userAvatar:'',
    showShareImg: false,
    bg:""
  },

  ready: function() {
    
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //下载diy图片
    getDiy: function (hasPost) {
     
      var that = this;
      this.data.diyImg = this.data.product.product.image[0].thumbImg;
      var config = wx.getStorageSync('config');
      this.data.site_name = config ? config[2].value : '';
      that.setData({
        showpost: true
      })
      if (hasPost) {
        return false;
      }
      wx.showLoading({
        title: '正在加载图片',
        mask: true,
      });
      var diyImg = that.data.diyImg;
      if (diyImg) {
        wx.downloadFile({
          url: diyImg,
          success: function(res) {
            if (res.statusCode === 200) {
              var imgSrc = res.tempFilePath;
              that.calculateImg(imgSrc, function(data) {
                that.setData({
                  diyImg: imgSrc,
                  diyImgInfo : data
                });
                that.getQrcode();
              })
            } else {
              wx.showToast({
                title: '个性图片下载失败！',
                icon: 'none',
                duration: 2000,
                success: function() {
                  that.getQrcode();
                }
              })
            }
          }
        })
      } else {
        that.getQrcode();
      }
    },
    //
    getQrcode:function(){
      var that = this;
      var qrCode = '';
      var user = wx.getStorageSync('userInfo');
      var pid = user.id;
      if(!pid){
        pid = wx.getStorageSync('uid');
      }
      var param ={
        page: 'pages/product/product',
        scene: that.data.product.product.product_id + '&' + pid
      } 
      product.qrcode(param, (res) => {
        if(res.status != 1){
          wx.showToast({
            title: '二维码生成失败，请稍后重试',
            icon: 'none',
            duration: 2000
          })
          setTimeout(function () {
            that.closePoste(false);
          }, 2000)
        }else{
          qrCode = res.data;
          wx.downloadFile({
            url: qrCode,
            success: function (res) {
              if (res.statusCode === 200) {
                var imgSrc = res.tempFilePath;
                that.setData({
                  qrCode: imgSrc
                });
                that.getAvatar();
              } else {
                wx.showToast({
                  title: '二维码下载失败！',
                  icon: 'none',
                  duration: 2000,
                  success: function () {
                    that.getAvatar();
                  }
                })
              }
            }
          })
        }
      })
    },
    getAvatar:function(){
      var that = this;
      var avatarUrl = that.data.user.avatarUrl;
      if (avatarUrl) {
        wx.downloadFile({
          url: avatarUrl,
          success: function (res) {
            if (res.statusCode === 200) {
              var imgSrc = res.tempFilePath;
              that.setData({
                userAvatar: imgSrc
              });
              that.sharePosteCanvas();
            } else {
              wx.showToast({
                title: '微信头像下载失败！',
                icon: 'none',
                duration: 2000,
                success: function () {
                  that.sharePosteCanvas();
                }
              })
            }
          }
        })
      } else {
       
        that.sharePosteCanvas();
      }
    },
    //canvas绘制分享海报
    sharePosteCanvas: function () {
      var config = wx.getStorageSync('config');
      wx.hideLoading();
      var imgInfo = this.data.diyImgInfo;
      wx.showLoading({
        title: '生成中...',
        mask: true,
      })
      var that = this;
      const ctx = wx.createCanvasContext('myCanvas', that);
      var width = "";
      const query = wx.createSelectorQuery().in(this);
      query.select('#canvas-container').boundingClientRect(function(rect) {
        if (imgInfo) {
          var imgheight = parseFloat(imgInfo);
        }
        var user = that.data.user;
        var height = rect.height;
        var right = rect.right;
        width = rect.width;
        var left = rect.left;
        //画布白色背景
        ctx.setFillStyle('#fff');
        ctx.fillRect(0, 0, width, height);
        // 商品名称
        var name = that.data.product.product.name;
        //商品图片
        if (that.data.diyImg) {
          ctx.drawImage(that.data.diyImg, 0, 0, width, imgheight ? imgheight : width);
        }
        //商品名称
        var rs = that.textByteLength(name,30);
        var len = rs[1].length > 2 ? 2 : rs[1].length;
        for(var i = 0; i< len ;i++){
          var line = i +1 ;
          var top = imgheight + (18*line);
          ctx.setFontSize(14);
          ctx.setFillStyle('#333');
          ctx.fillText(rs[1][i], left - 10, top);
        }
       
        //  个人头像
        if (that.data.userAvatar) {
          ctx.drawImage(that.data.userAvatar, left -10 , imgheight + 50,35,35)
          ctx.setFontSize(12);
          ctx.setFillStyle('#000');
          var name = user.username ? user.username : user.nickName;
          if (name) {
            ctx.fillText(name, left + 35, imgheight + 72);
          }
        }
        //站点名称
        ctx.setFillStyle('#fec67d');
        ctx.fillText(that.data.site_name, left -10, imgheight + 107);
        //二维码
        if (that.data.qrCode) {
          ctx.drawImage(that.data.qrCode, right - 120 , imgheight+10,100,100)
          ctx.setFontSize(12);
          ctx.setFillStyle('#000');
        }
      }).exec()
      setTimeout(function() {
        ctx.draw();
        wx.hideLoading();
        that.setData({
          showShareImg:true
        })
      }, 500)

    },

    textByteLength(text, num) { // text为传入的文本  num为单行显示的字节长度
      let strLength = 0; // text byte length
      let rows = 1;
      let str = 0;
      let arr = [];
      for (let j = 0; j < text.length; j++) {
        if (text.charCodeAt(j) > 255) {
          strLength += 2;
          if (strLength > rows * num) {
            strLength++;
            arr.push(text.slice(str, j));
            str = j;
            rows++;
          }
        } else {
          strLength++;
          if (strLength > rows * num) {
            arr.push(text.slice(str, j));
            str = j;
            rows++;
          }
        }
      }
      arr.push(text.slice(str, text.length));
      return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
    },

    //点击保存到相册
    saveShareImg: function() {
      var that = this;
      wx.showLoading({
        title: '正在保存',
        mask: true,
      })
      setTimeout(function() {
        wx.canvasToTempFilePath({
          canvasId: 'myCanvas',
          success: function(res) {
            wx.hideLoading();
            var tempFilePath = res.tempFilePath;
            wx.saveImageToPhotosAlbum({
              filePath: tempFilePath,
              success(res) {
                wx.showModal({
                  content: '图片已保存到相册，赶紧晒一下吧~',
                  showCancel: false,
                  confirmText: '好的',
                  confirmColor: '#333',
                  success: function(res) {
                    that.closePoste();
                    if (res.confirm) {
                    }
                  },
                  fail: function(res) {
                    console.log(res)
                  }
                })
              },
              fail: function(res) {
                wx.showToast({
                  title: res.errMsg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          },
          fail: function(err) {
            console.log(err)
          }
        }, that);
      }, 1000);
    },
    //关闭海报
    closePoste: function(status = true ) {
      this.setData({
        showpost: false
      })
      this.triggerEvent('myevent',{'status':status})
    },

    //计算图片尺寸
    calculateImg: function(src, cb) {
      var that = this;
      wx.getImageInfo({
        src: src,
        success(res) {
          wx.getSystemInfo({
            success(res2) {
              var ratio = res.width / res.height;
              var imgHeight = (res2.windowWidth * 0.85 / ratio) + 120; //画布的高度
              that.setData({
                imgHeight: imgHeight
              })
              cb(imgHeight - 120);  //返回图片的高度
            }
          })
        }
      })
    }
  }
})